const WebSocket = require('ws');
const uuidv4 = require('uuid').v4;

const ws1 = new WebSocket.WebSocketServer({ noServer: true });

ws1.on('connection', (ws, req) => {
    console.log('连接成功');
    const uuid = uuidv4();
    ws.uuid = uuid; // 标识用户id
    const user = {
        context: 'user',
        uuid
    }
    // console.log(JSON.stringify(user));
    ws.send(JSON.stringify(user));
    
    ws.on('message', (data) => {
        console.log('收到消息');
        console.log(JSON.parse(data));
        const message = JSON.parse(data);
        const newMessage = {
            context: 'message',
            uuid: message.uuid,
            content: message.content,
        };
        // ws.send(JSON.stringify(newMessage));
        broadcastMessage(newMessage);
    })
});

function broadcastMessage(message) {
    ws1.clients.forEach((client) => {
        if (client.readyState === WebSocket.OPEN && client.uuid !== message.uuid) {
            client.send(JSON.stringify(message));
        }
    });
}
module.exports = ws1;